<?php

/**
 * @Author: wuchenge
 * @Date:   2021-12-10 17:36:38
 * @Email: ligui0506@126.com
 * @Descript:
 */
namespace App\Admin\Controllers;

use App\Http\Controllers\ApiController;
use App\Libraries\JwtToken;
use App\Models\Admin\Admin;
use App\Requests\Admin\LoginRequest;
use App\Transformer\AdminTransformer;
use Illuminate\Http\Request;

class IndexController extends ApiController
{
    protected $admin_transformer;

    public function __construct(AdminTransformer $admin_transformer)
    {
        $this->admin_transformer = $admin_transformer;
    }

    public function info(Request $request)
    {
        return $this->response($this->admin_transformer->transform($request->get('admin')));
    }

    public function login(LoginRequest $request)
    {
        // 帐号
        $username = $request->input('username');
        // 密码
        $password = $request->input('password');

        if (!config('app.debug')) {
            // 验证图片码
            if (!captcha_api_check($request->captcha, $request->key)) {
                return $this->setErrorCode(1, '验证码错误')->response();
            }
        }

        $admin = Admin::where('username', $username)->first();

        if (!$admin) {
            return $this->setErrorCode(1, '没有找到此用户')->response();
        }

        if ($admin->password != Admin::encodePassword($password)) {
            return $this->setErrorCode(1, '密码错误')->response();
        }

        if ($admin->status == Admin::STATUS_NO) {
            return $this->setErrorCode(1, '用户被禁用')->response();
        }

        // 更新最后登录时间
        $admin->fill(['updated_at' => date('Y-m-d H:i:s')])->save();

        $payload = [
            'id'        => $admin->id,
            'nick_name' => $admin->nickname,
        ];

        $data = [
            'token' => JwtToken::createToken($payload),
            'admin' => $this->admin_transformer->transform($admin),
        ];

        return $this->response($data);
    }

    public function captcha()
    {
        return $this->response(app('captcha')->create('default', true));
    }
}
